package com.datamation.swadeshi.view;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.Toast;

import com.datamation.swadeshi.R;
import com.datamation.swadeshi.adapter.SetTitleAdapter;
import com.datamation.swadeshi.adapter.VanInvoiceHistoryAdapter;
import com.datamation.swadeshi.control.SalesPrintPreviewAlertBox;
import com.datamation.swadeshi.control.VanSalePrintPreviewAlertBox;
import com.datamation.swadeshi.control.data.InvDetDS;
import com.datamation.swadeshi.control.data.InvHedDS;
import com.datamation.swadeshi.model.InvHed;
import com.datamation.swadeshi.model.OrdHed;

public class FragmentSalesManagementVanSaleInvoice extends Fragment {
	View view;
	
	ListView lvInvoiceList;
	
	//InvoiceDS invoiceDS;
	//InvoiceItemAdapter invoiceItemAdapter;
	ArrayList<InvHed> arrayList;
	//Customer nearbyCustomer;
	
	@Override	
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.sales_mangemet_van_sales_invoice, container, false);
		
		lvInvoiceList = (ListView) view.findViewById(R.id.lvPhoneInvoiceList);
		registerForContextMenu(lvInvoiceList);
		
		getActivity().getActionBar().removeAllTabs();
		getActivity().getActionBar().setNavigationMode(0);
		
		setHasOptionsMenu(true);
       
		SetTitleAdapter adapter =new SetTitleAdapter();
		adapter.createCutomActionBarTitle("Invoice - Van", getActivity());
		
		//display
		displayInvoiceHistory();
	
//		lvInvoiceList.setOnItemClickListener(new OnItemClickListener() {
//
//			@Override
//			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//			//	MainActivity activity = (MainActivity) getActivity();
//			//	activity.currentlySelectedInvoice = invoiceDS.getInvoiceByID(invoiceList.get(position).getInvoice_id());
//				
//				/*FragmentTransaction transaction = getFragmentManager().beginTransaction();
//				transaction.replace(R.id.frame_container, new PhoneInvoiceInfoFragment());
//				transaction.addToBackStack(null);
//				transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
//				transaction.commit();*/
//				
//			}
//		});
		
//		lvInvoiceList.setOnItemLongClickListener(new OnItemLongClickListener() {
//
//			@Override
//			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//				
//				 InvHed invHed = arrayList.get(position);
//	        	 delete(getActivity(), invHed.getFINVHED_REFNO());
//												
//				return false;
//			}
//		});
		
		//back button disable 
        view.setFocusableInTouchMode(true);
        view.requestFocus();
        view.setOnKeyListener(new View.OnKeyListener() {
		        @Override
		        public boolean onKey(View v, int keyCode, KeyEvent event) {
		            Log.i("", "keyCode: " + keyCode);
		            if( keyCode == KeyEvent.KEYCODE_BACK ) {
		            	
		            	Toast.makeText(getActivity(),"Back Navigationid is disable", Toast.LENGTH_SHORT).show();
		               // getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
		                return true;
		            }else if ((keyCode == KeyEvent.KEYCODE_HOME)) {
		    			
		    			getActivity().finish();
		    			
		    			return true;

		    		} else {
		                return false;
		            }
		        }
		    });
        
        
		return view;
	}
	
	
	
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
	      super.onCreateContextMenu(menu, v, menuInfo);
	      if (v.getId()==R.id.lvPhoneInvoiceList) {
	          MenuInflater inflater = getActivity().getMenuInflater();
	          inflater.inflate(R.menu.menu_list, menu);
	      }
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
	     AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	     InvHed ordHed = arrayList.get(info.position);
	      switch(item.getItemId()) {
	         case R.id.cancel:
	        	// TODO Auto-generated method stub
				
	        	 delete(getActivity(), ordHed.getFINVHED_REFNO());
				
	            return true;
	            
	          case R.id.print:
	            // print stuff here
	        	  setBluetooth(true);
	        	  VanSalePrintPreviewAlertBox alertBox=new VanSalePrintPreviewAlertBox(getActivity());
				  alertBox.PrintDetailsDialogbox(getActivity(), "",ordHed.getFINVHED_REFNO());
	        	  
	          return true;
	            default:
	                return super.onContextItemSelected(item);
	      }
	}
	
	
	
	private void delete(final Context context,final String refno){

		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
		//alertDialogBuilder.setTitle(title);
		alertDialogBuilder.setMessage("Are you sure you want to delete this entry?");
		final InvHedDS invHedDS =new InvHedDS(getActivity());
		final InvDetDS detDS=new InvDetDS(getActivity());
		alertDialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);
		alertDialogBuilder
				.setCancelable(false)
				.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								
								//delete data
								try {
									invHedDS.restData(refno); //FORDHED DATA
								}catch(Exception e){
									Log.w("delete FORDHED Data Erorrrr ", e.toString());
								}
								try {
									detDS.restData(refno); // FORDDET DATA
								}catch(Exception e){
									Log.w("delete FORDDET Data Erorrrr ", e.toString());
								}finally{
									displayInvoiceHistory();
								}

							}
					})
				.setNegativeButton("No",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,	int id) {
								dialog.cancel();
							}
						});
		
		AlertDialog alertD = alertDialogBuilder.create();

		alertD.show();
	}
	
	private void displayInvoiceHistory() {
		// TODO Auto-generated method stub
		lvInvoiceList = (ListView) view.findViewById(R.id.lvPhoneInvoiceList);
		lvInvoiceList.clearTextFilter();
		InvHedDS hedDS = new InvHedDS(getActivity());
		arrayList = hedDS.getAllUnsyncedInvHed("");
		lvInvoiceList.setAdapter(new VanInvoiceHistoryAdapter(getActivity(), arrayList));
	}




	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		
		for(int i = 0; i < menu.size(); ++i){
			menu.removeItem(menu.getItem(i).getItemId());
		}
		
		inflater.inflate(R.menu.frag_invoice_phone_menu, menu);
		SearchView searchView = (SearchView) menu.findItem(R.id.action_customer_search_phone).getActionView();
		searchView.setOnQueryTextListener(new OnQueryTextListener() {
			
			@Override
			public boolean onQueryTextSubmit(String query) {
				return false;
			}
			
			@Override
			public boolean onQueryTextChange(String newText) {
				
				lvInvoiceList = (ListView) view.findViewById(R.id.lvPhoneInvoiceList);
				lvInvoiceList.clearTextFilter();
				InvHedDS hedDS = new InvHedDS(getActivity());
				arrayList = hedDS.getAllUnsyncedInvHed(newText);
				lvInvoiceList.setAdapter(new VanInvoiceHistoryAdapter(getActivity(), arrayList));

				return false;
			}
		});
		
		super.onCreateOptionsMenu(menu, inflater);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId() == R.id.action_invoice_phone_new){
			FragmentTransaction transaction = getFragmentManager().beginTransaction();
			transaction.replace(R.id.frame_container, new FragmentSalesManagementVanSales());
			transaction.addToBackStack(null);
			transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
			transaction.commit();
		}
		return super.onOptionsItemSelected(item);
	}
	
	public static boolean setBluetooth(boolean enable) {
	    BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
	    boolean isEnabled = bluetoothAdapter.isEnabled();
	    if (enable && !isEnabled) {
	        return bluetoothAdapter.enable(); 
	    }
	    else if(!enable && isEnabled) {
	        return bluetoothAdapter.disable();
	    }
	    // No need to change bluetooth state
	    return true;
	}
	

}
